package interview;

import java.util.*;

public class lc3 {
    public static void main(String[] args) {
        System.out.println(lengthOfLongestSubstring2("abcabc"));
    }
    public static int lengthOfLongestSubstring(String s) {
        int n = s.length();
        int max_len = 0;
        Map<Character,Integer> map = new HashMap();
        for (int i = 0, j = 0; j < n; j++) {
            if(map.containsKey(s.charAt(j))){
                i = Math.max(map.get(s.charAt(j)), i);
            }
            max_len = Math.max(max_len, j - i);
            map.put(s.charAt(j), j);
        }
        return max_len;
    }
    public static int lengthOfLongestSubstring2(String s) {
        //滑动窗口
        //flag相当于hash表
        int[] flag = new int[128];
        int start = 0, end = 0;
        int ans = 0;
        while(end < s.length()){
            //没有重复直接右边移动
            if(flag[s.charAt(end)] == 0){
                flag[s.charAt(end)] = 1;
                end++;
            }
            //有重复左边一直移动到重复的下一个
            else{
                flag[s.charAt(start)] = 0;
                start++;
            }
            ans = Math.max(ans, end - start);
        }
        return ans;
    }
}
